package com.bootdo.websocket;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
//https://blog.csdn.net/Phoenix_smf/article/details/89227172
//shiro权限拦截不要放在验证权限的后面 这样不生效
@ServerEndpoint("/websocket/{cid}")
@Component
public class WebSocketServer {





    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
    public static ConcurrentHashMap<Long, WebSocketServer> SOCKER_MAPING = new ConcurrentHashMap();
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    //接收sid
    private String cid="";
    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("cid") String cid) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        this.cid=cid;
        System.err.println("有连接加入"+cid);
        SOCKER_MAPING.put(Long.parseLong(cid), this);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        SOCKER_MAPING.remove(this.cid);
    }


    @OnMessage
    public void onMessage(String message, Session session) {
        //System.err.println("收到消息"+message);
        //群发消息
       /* for (WebSocketServer item : webSocketSet) {
            item.sendMessage(message);
        }*/
       try {
           JSONObject jsonObject = (JSONObject) JSONObject.parse(message);
           if(jsonObject.getIntValue("type") == 1){
               session.getBasicRemote().sendText(message);
           }
       }catch (Exception e){

       }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        SOCKER_MAPING.remove(this.cid);
        error.printStackTrace();
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message)   {

        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 群发自定义消息
     **/
    public static void sendAllMessage(String message)  {
        for (WebSocketServer item : webSocketSet) {
            //这里可以设定只推送给这个sid的，为null则全部推送
            try {
                item.sendMessage(message);
            }catch (Exception e){
                SOCKER_MAPING.remove(item.cid);
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

}
